package visao;

import java.io.Serializable;
import modelo.Uf;
import visao.util.JsfUtil;
import sessaobean.UfFacade;

import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name="ufController")
@SessionScoped
public class UfController implements Serializable{

    private Uf selected;
    private DataModel items = null;

    @EJB
    private sessaobean.UfFacade ejbFacade;

    public DataModel getListarUf(){
        
        List<Uf> listUf = ejbFacade.findAll();
        items = new ListDataModel(listUf);
        return items;
        
    }
    
    public void setSelected(Uf selected){
        this.selected = selected;
    }

    public Uf getSelected() {
        return selected;
    }

    private UfFacade getFacade() {
        return ejbFacade;
    }

    public void prepareCreate(ActionEvent actionEvent) {
        selected = new Uf();
    }

    public void prepareEdit(ActionEvent actionEvent) {
        selected = (Uf) (items.getRowData());
    }

    public void create(ActionEvent actionEvent) {
        try {
            getFacade().create(selected);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UfCreated"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public void update(ActionEvent actionEvent) {
        try {
            getFacade().edit(selected);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UfUpdated"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public void destroy(ActionEvent actionEvent) {
        Uf tempUf = (Uf) (items.getRowData());
        try {
            getFacade().remove(tempUf);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UfDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
}